﻿using LbangCMS.Areas.Admin.Models;
using LbangCMS.EFModels;
using LbangCMS.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace LbangCMS.Areas.Admin.Controllers
{
    [Authorize]
    public class ContentController : Controller
    {
        // GET: Admin/Content
        public ActionResult List(int categoryId=0,int pageIndex=1,int pageSize=12)
        {
            int totalPage;
            var contents = GetList(categoryId, pageIndex, pageSize,out totalPage);
            var data = new List<ContentModel>();
            var model = new ContentListModel();
            if(contents!=null&contents.Any())
            {
                foreach (var item in contents)
                {
                    var m = new ContentModel();
                    m.ID = item.ID;
                    m.CategoryId = item.CategoryId;
                    m.Title = item.Title;
                    m.Summary = item.Summary;
                    m.CoverSrc = item.CoverSrc;
                    m.PublishTime = item.PublishTime;
                    data.Add(m);
                }
                model.ContentList = data;
                model.PageIndex = pageIndex;
                model.TotalPage = totalPage;


            }
            if (Request.IsAjaxRequest())
            {
                return PartialView("_ListPartial", model);
            }
            else
            {
                return View(model);
            }
        }

        public ActionResult Edit(int id=0)
        {
            var contentCategories = GetCategoryList();
            if (contentCategories != null && contentCategories.Any())
            {
                var categoryModel = new List<ContentCategoryModel>();
                foreach (var item in contentCategories)
                {
                    categoryModel.Add(new ContentCategoryModel { ID = item.ID, Name = item.Name });
                }
                ViewBag.Categories = categoryModel;
            }
            if (id>0)
            {
                var content = GetContent(id);
                if(content!=null)
                {
                    var model = new ContentModel();
                    model.ID = content.ID;
                    model.CategoryId = content.CategoryId;
                    model.Title = content.Title;
                    model.Summary = content.Summary;
                    model.CoverSrc = content.CoverSrc;
                    model.IsHasCover = content.IsHasCover;
                    model.Source = content.Source;
                    model.Status = content.Status==1;
                    model.Body = content.Body;
                    model.PublishTime = content.PublishTime;
                    return View(model);
                }
            }
            return View();
        }

        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Edit(ContentModel model)
        {
            if(ModelState.IsValid)
            {
                if(model.ID>0)
                {
                    UpdateContent(model.ID, model.CategoryId, model.Title, model.Summary, model.CoverSrc, model.IsHasCover, model.Source, model.Status?1:0, model.Body, model.PublishTime);
                }
                else
                {
                    AddContent(model.CategoryId, model.Title, model.Summary, model.CoverSrc, model.IsHasCover, model.Source, model.Status?1:0, model.Body, model.PublishTime);
                }
                return Json(new { success = true });
            }
            else
            {
                return Json(new { success = false, errorMsg = ModelState.ToHtmlMessage() });
            }
            
        }


        public ActionResult Remove(int id)
        {
            RemoveContent(id);
            return Json(new { success = true });
        }

        private List<ContentCategory> GetCategoryList()
        {
            using (var db = new Database())
            {
                return db.ContentCategories.OrderBy(o => o.SortIndex).ToList();
            }
        }

        private List<Content> GetList(int categoryId,int pageIndex,int pageSize,out int totalPage)
        {
            using (var db = new Database())
            {
                if (categoryId > 0)
                {
                    var count = db.Contents.Where(o => o.CategoryId == categoryId).Count();
                    totalPage = (int)Math.Ceiling(count / (pageSize * 1M));
                    return db.Contents.Where(o => o.CategoryId == categoryId).OrderByDescending(o => o.ID).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                }
                else
                {
                    var count = db.Contents.Count();
                    totalPage = (int)Math.Ceiling(count / (pageSize * 1M));
                    return db.Contents.OrderByDescending(o => o.ID).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
                }
            }
        }

        private void RemoveContent(int id)
        {
            using (var db = new Database())
            {
                var content = db.Contents.Where(o => o.ID == id).FirstOrDefault();
                if(content!=null)
                {
                    db.Contents.Remove(content);
                    db.SaveChanges();
                }
            }
        }

        private Content GetContent(int id)
        {
            using (var db = new Database())
            {
                return db.Contents.Where(o => o.ID == id).FirstOrDefault();
            }
        }

        public void AddContent(int categoryId, string title, string summary, string coverSrc, bool isHasCover, string source, int status, string body, string publishTime)
        {
            using (var db = new Database())
            {
                var content = new Content();

                content.Title = title;
                content.CategoryId = categoryId;
                content.Summary = summary;
                content.IsHasCover = isHasCover;
                content.CoverSrc = coverSrc;
                content.Source = source;
                content.Status = status;
                content.Body = body;
                content.PublishTime = publishTime;
                content.CreateTime = DateTime.Now;
                db.Contents.Add(content);
                db.SaveChanges();

            }
        }

        private void UpdateContent(int id,int categoryId,string title,string summary,string coverSrc,bool isHasCover,string source,int status,string body,string publishTime)
        {
            using (var db = new Database())
            {
                var content = db.Contents.Where(o => o.ID == id).FirstOrDefault();
                if (content != null)
                {
                    content.Title = title;
                    content.CategoryId = categoryId;
                    content.Summary = summary;
                    content.IsHasCover = isHasCover;
                    content.CoverSrc = coverSrc;
                    content.Source = source;
                    content.Status = status;
                    content.Body = body;
                    content.PublishTime = publishTime;
                    db.SaveChanges();
                }
            }
        }

    }
}